\NeedsTeXFormat{LaTeX2e}
\ProvidesPackage{lstlinebgrd}[2018/08/05v1.00 well-designed (TeX)]
\RequirePackage{listings}
\RequirePackage{xcolor}

% Patch line number key to call line background macro
\lst@Key{numbers}{none}{%
    \def\lst@PlaceNumber{\lst@linebgrd}%
    \lstKV@SwitchCases{#1}%
    {none&\\%
     left&\def\lst@PlaceNumber{\llap{\normalfont
                \lst@numberstyle{\thelstnumber}\kern\lst@numbersep}\lst@linebgrd}\\%
     right&\def\lst@PlaceNumber{\rlap{\normalfont
                \kern\linewidth \kern\lst@numbersep
                \lst@numberstyle{\thelstnumber}}\lst@linebgrd}%
    }{\PackageError{Listings}{Numbers #1 unknown}\@ehc}}

% New keys
\lst@Key{linebackgroundcolor}{}{%
    \def\lst@linebgrdcolor{#1}%
}
\lst@Key{linebackgroundsep}{0pt}{%
    \def\lst@linebgrdsep{#1}%
}
\lst@Key{linebackgroundwidth}{\linewidth}{%
    \def\lst@linebgrdwidth{#1}%
}
\lst@Key{linebackgroundheight}{\ht\strutbox}{%
    \def\lst@linebgrdheight{#1}%
}
\lst@Key{linebackgrounddepth}{\dp\strutbox}{%
    \def\lst@linebgrddepth{#1}%
}
\lst@Key{linebackgroundcmd}{\color@block}{%
    \def\lst@linebgrdcmd{#1}%
}


% Line Background macro
\newcommand{\lst@linebgrd}{%
    \ifx\lst@linebgrdcolor\empty\else
    \rlap{%
        \lst@basicstyle
        \color{-.}% By default use the opposite (`-`) of the current color (`.`) as background
        \lst@linebgrdcolor{%
        \kern-\dimexpr\lst@linebgrdsep\relax%
        \lst@linebgrdcmd{\lst@linebgrdwidth}{\lst@linebgrdheight}{\lst@linebgrddepth}%
        }%
    }%
    \fi
}
% 使用示例
%\begin{lstlisting}[language=C,basicstyle=\ttfamily,linebackgroundcolor={\ifodd\value{lstnumber}\color{green}\fi}]
%/**
%* Prints Hello World.
%**/
%#include <stdio.h>
%
%int main(void) {
%   printf("Hello World!");
%   return 0;
%}
%\end{lstlisting}
%
%\begin{lstlisting}[language=C,basicstyle=\ttfamily\Large,linebackgroundcolor={\ifodd\value{lstnumber}\color{green}\else\color{yellow}\fi},linebackgroundsep=1em,linebackgroundwidth=18em]
%/**
%* Prints Hello World.
%**/
%#include <stdio.h>
%
%int main(void) {
%   printf("Hello World!");
%   return 0;
%}
%\end{lstlisting}
%
%\begin{lstlisting}[language=C,basicstyle=\ttfamily\tiny,linebackgroundcolor={\color{blue!\the\numexpr 5*\value{lstnumber}\relax}},linebackgroundheight=1.7ex,linebackgrounddepth=.4ex]
%/**
%* Prints Hello World.
%**/
%#include <stdio.h>
%
%int main(void) {
%   printf("Hello World!");
%   return 0;
%}
%/**
%* Prints Hello World.
%**/
%#include <stdio.h>
%
%int main(void) {
%   printf("Hello World!");
%   return 0;
%}
%\end{lstlisting}